# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Integrations::ChatMessage::VulnerabilityMessage do
  subject { described_class.new(args) }

  let(:args) do
    {
      project_name: 'Foobar Project',
      project_url: 'https://git.example.com/random/foobar',
      object_attributes: {
        url: 'https://git.example.com/random/foobar/-/security/vulnerabilities/1',
        title: 'Foo Vulnerability',
        identifiers: [
          {
            name: 'CVE-2021-1234',
            external_id: 'CVE-2021-1234',
            external_type: 'cve',
            url: 'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-1234'
          },
          {
            name: 'CVE-2021-5678',
            external_id: 'CVE-2021-5678',
            external_type: 'cve',
            url: 'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-5678'
          }

        ]
      }
    }
  end

  it_behaves_like Integrations::ChatMessage

  describe '#message' do
    it 'returns the correct message' do
      expect(subject.message).to eq("Vulnerability detected in [Foobar Project](https://git.example.com/random/foobar)")
    end
  end

  describe '#attachments' do
    it 'returns an array of one' do
      expect(subject.attachments).to be_a(Array)
      expect(subject.attachments.size).to eq(1)
    end

    it 'contains the correct attributes' do
      attachments_item = subject.attachments.first
      expect(attachments_item).to have_key(:title)
      expect(attachments_item).to have_key(:title_link)
      expect(attachments_item).to have_key(:color)
      expect(attachments_item).to have_key(:fields)
    end

    it 'returns the correct color' do
      expect(subject.attachments.first[:color]).to eq("#C95823")
    end

    it 'returns the correct attachment fields' do
      attachments_item = subject.attachments.first
      fields = attachments_item[:fields].map { |h| h[:title] }

      expect(fields).to match_array(%w[Severity Identifiers])
    end

    it 'returns list of identifiers in correct form' do
      identifiers_item = subject.attachments.first[:fields].detect { |i| i[:title] == 'Identifiers' }
      expect(identifiers_item[:value]).to eq('<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-1234|CVE-2021-1234>, <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-5678|CVE-2021-5678>')
    end
  end
end
